<?

/* --|   COMMON
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class common {
    const PATH = 'data/common/';
    /* -----------------------------------------------------------------------
      EDITORIAL FUNCTIONS
      ------------------------------------------------------------------------ */

    /**
     * SET
     *
     * @param array $a [title,description,keywords,copyright,foonote]
     * @return result object
     */
    public static function set(array $a) {
        if (!EDITOR)
            return common::result(600, dgettext('common', 'Access denied'));
        if (!is_writable(self::PATH))
            return common::result(800, dgettext('common', 'Writing is not permited'));
        $a['keywordstring'] = $a['keywords'];
        $a['keywords'] = preg_split('/,/', $a['keywords'], 10, PREG_SPLIT_NO_EMPTY);
        if ($a['keywords'])
            foreach ($a['keywords'] as $i)
                $a['keywords'][] = trim($i);
        $a = json_encode($a);
        file_put_contents(self::PATH . LANG . '_home.json', $a);
        cache::del('home[' . LANG . '][data]');
        return common::result(200, dgettext('common', 'Project data has been saved'));
    }

    /**
     * GET
     *
     * @return result object
     */
    public static function get() {
        $c = cache::get('home[' . LANG . '][data]');
        if (!$c) {
            $c = @file_get_contents(self::PATH . LANG . '_home.json');
            cache::set('home[' . LANG . '][data]', $c);
            if (!$c) {
                $c = cache::get('home[' . DEFLANG . '][data]');
                if (!$c) {
                    $c = @file_get_contents(self::PATH . DEFLANG . '_home.json');
                    if ($c)
                        cache::set('home[' . DEFLANG . '][data]', $c);
                }
            }
        }
        return json_decode($c);
    }

    public static function info($apps) {
        return @simplexml_load_file(self::PATH . 'info.xml');
    }

    public static function check($apps) {
        $check = new stdClass();
        $check->version->title = _('Versions');
        $check->version->php->title = _('PHP');
        $check->version->php->status = (floatval(phpversion()) >= 5);
        $check->version->php->msg = phpversion();
        // check extensions
        $check->ext->title = _('Extensions');
        $check->ext->safemod->title = _('PHP Safe mode');
        $check->ext->safemod->status = !ini_get('safe_mode');
        $check->ext->safemod->msg = $check->ext->safemod->status ? _('Installed') : _('Missing');
        $check->ext->rewrite->title = _('Mod Rewirite (Apache mod_rewrite)');
        $check->ext->rewrite->status = in_array('mod_rewrite', @apache_get_modules());
        $check->ext->rewrite->msg = $check->ext->rewrite->status ? _('Installed') : _('Missing');
        $check->ext->mysql->title = _('MySQL (php5_mysql)');
        $check->ext->mysql->status = extension_loaded('mysql');
        $check->ext->mysql->msg = $check->ext->mysql->status ? _('Installed') : _('Missing');
        $check->ext->apc->title = _('APC (php_apc)');
        $check->ext->apc->status = extension_loaded('apc');
        $check->ext->apc->msg = $check->ext->apc->status ? _('Installed') : _('Missing');
        $check->ext->json->title = _('JSON (php5_json) ');
        $check->ext->json->status = extension_loaded('json');
        $check->ext->json->msg = $check->ext->json->status ? _('Installed') : _('Missing');
        $check->ext->simplexml->title = _('SimpleXML (php5_simplexml) ');
        $check->ext->simplexml->status = extension_loaded('SimpleXML');
        $check->ext->simplexml->msg = $check->ext->simplexml->status ? _('Installed') : _('Missing');
        $check->ext->imagick->title = _('Imagick (php5_imagick)');
        $check->ext->imagick->status = extension_loaded('imagick');
        $check->ext->imagick->msg = $check->ext->imagick->status ? _('Installed') : _('Missing');
        $check->ext->geoip->title = _('GeoIP (php5_geoip)');
        $check->ext->geoip->status = extension_loaded('geoip');
        $check->ext->geoip->msg = $check->ext->geoip->status ? _('Installed') : _('Missing');
        // check data folder write access
        $check->folder->title = _('Permissions');
        $check->folder->data->title = sprintf(_('%s folder permission'), '"data/"');
        $check->folder->data->status = is_writable('./data');
        $check->folder->data->msg = $check->folder->data->status ? _('Writing is permitted.') : _('Writing is not permited.');
        // check applications
        $check->app->title = _('Applications');
        foreach ($apps as $i)
            $check->app->$i = self::application('check', $i);
        // check project _conf
        $check->project->title = _('Project Configuration');
        $check->project->name->title = _('Project name');
        $check->project->name->status = true;
        $check->project->name->msg = NAME;

        $check->project->domain->title = _('Project domain');
        $check->project->domain->status = DOMAIN;
        $check->project->domain->msg = DOMAIN ? DOMAIN : _('null');

        $check->project->cookieless->title = _('Project cookieless domain');
        $check->project->cookieless->status = COOKIELESS;
        $check->project->cookieless->msg = COOKIELESS ? COOKIELESS : _('null');

        $check->project->setup->title = _('Setup');
        $check->project->setup->status = !SETUP;
        $check->project->setup->msg = SETUP ? _('enable') : _('disable');

        $check->project->debug->title = _('Debug Level');
        $check->project->debug->status = DEBUG > 5;
        $check->project->debug->msg = DEBUG;


        $check->project->deflang->title = _('Default language');
        $check->project->deflang->status = DEFLANG ? true : false;
        $check->project->deflang->msg = DEFLANG ? DEFLANG : null;

        $check->project->multilang->title = _('Multi language');
        $check->project->multilang->status = true;
        $check->project->multilang->msg = MULTILANGUAGE ? _('enable') : _('disable');

        $check->project->deftheme->title = _('Default theme');
        $check->project->deftheme->status = true;
        $check->project->deftheme->msg = DEFTHEME;

        $check->project->analytics->title = _('Google Analytics');
        $check->project->analytics->status = true;
        $check->project->analytics->msg = ANALYTICS;

        $check->project->alexa->title = _('Alexa');
        $check->project->alexa->status = true;
        $check->project->alexa->msg = ALEXA;

        $check->project->webmaster->title = _('Google Webmaster');
        $check->project->webmaster->status = true;
        $check->project->webmaster->msg = WEBMASTER;

        $check->project->siteexplorer->title = _('Yahoo Site Explorer');
        $check->project->siteexplorer->status = true;
        $check->project->siteexplorer->msg = SITEEXPLORER;

        return $check;
    }

    public static function application($cmd, $app, $SETUP = SETUP) {
        $data = new stdClass();
        $data->title = $app;
        $data->status = true;
        //echo $app.'<br>';
        if (!is_dir('apps/' . $app)) {
            $data->status = false;
            $data->msg = _('Application can not be found');
            return $data;
        }
        if (!is_writable('./data')) {
            $data->status = false;
            $data->msg = sprintf(_('Writing is not permitted in %s folder'), '"data/"');
            return $data;
        }
        $setup = @simplexml_load_file('apps/' . $app . '/_setup/setup.xml');
        switch ($cmd) {
            case 'check':
                if ($setup) {
                    // requirement apps
                    $requirement_applications = get_object_vars($setup->requirement_applications);
                    $applications = scandir('apps/');
                    $diff = array_diff((array) $requirement_applications['application'], (array) $applications);
                    if (count($diff)) {
                        $data->status = false;
                        $data->msg = sprintf(_('%s app/apps can not be found'), '"' . implode(", ", $diff) . '"');
                    }
                    // data folders
                    $data_folders = get_object_vars($setup->data_folders);
                    $folders = scandir('data/');
                    $diff = array_diff((array) $data_folders['folder'], (array) $folders);
                    if (count($diff)) {
                        $data->status = false;
                        $data->msg = sprintf(_('%s folder/folders can not be found'), '"' . implode(", ", $diff) . '"');
                    }
                    // database tables
                    $db_tables = get_object_vars($setup->db_tables);
                    //echo print_r(($db_tables),1).'<br/>';
                    $r = db::query(sprintf("SHOW TABLES LIKE '%s%%';", $app), true, true, 'mysqli_fetch_array');
                    if ($r)
                        foreach ($r as $i)
                            $tables[] = $i[0];
                    //echo print_r(($tables),1).'<br/>';
                    $diff = array_diff((array) $db_tables['table'], (array) $tables);
                    //echo print_r(($diff),1).'<br/>';
                    //exit;
                    if (count($diff)) {
                        $data->status = false;
                        $data->msg = sprintf(_('%s table/tables can not be found'), '"' . implode(", ", $diff) . '"');
                    }
                    if ($data->status)
                        $data->msg = _('Installed');
                    elseif ($SETUP)
                        $data = self::application('install', $app);
                } else {
                    $data->status = false;
                    $data->msg = _('Missing or broken setup file');
                }
                return $data;
                break;
            case 'install':
                foreach ($setup->data_folders as $i) {
                    @mkdir('data/' . $i->folder);
                }
                foreach (glob('apps/' . $app . '/_setup/*.sql') as $i) {
                    $dump = @file_get_contents($i);
                    if ($dump) {
                        preg_match_all('/^(SET|CREATE|INSERT)([^;]+[^\n]*);/mis', $dump, $queries);
                        foreach ($queries[0] as $query)
                            db::query($query);
                    }
                }
                return self::application('check', $app, false);
                break;
        }
    }

    public static function sitemap() {

    }

    public static function sitemaps($a) {

        $XML = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
XML;
        foreach ($a as $app) {
            $map = $app::sitemap();
            if ($map) {
                list($map, $url, $date) = array(DOMAIN . '/' . $map, DOMAIN . '/' . $app, @date('Y-m-d'));
                $XML .= <<<XML
<url>
      <loc>http://$url</loc>
      <lastmod>$date</lastmod>
</url>
<url>
      <loc>http://$map</loc>
      <lastmod>$date</lastmod>
</url>

XML;
            }
        }
        $XML .= <<<XML
</urlset>
XML;
        file_put_contents(self::PATH . 'sitemap.xml', $XML);
    }

    ########################################################
    ########################################################
    ########################################################

    public static function accessdenied($url = '/') {

        $data = array('code' => 600, 'status' => dgettext('common', 'Error'), 'message' => dgettext('common', 'Access Denied'));
        switch (FORMAT) {
            default:
                header("HTTP/1.1 401 Access Denied");
                echo file_get_contents('http://' . DOMAIN . '/account/accessdenied');
                break;
            case 'xml': header('content-type: text/xml');
                echo xml::convert($data);
                break;
            case 'json': header('content-type: text/javascript');
                echo json_encode($data);
                break;
            case 'text': header('content-type: text/plain');
                var_export($data);
                break;
        }
        exit;
        //header('location: '.$url,true,302);
    }

    public static function format(&$data) {
        switch (FORMAT) {
            default:
                $data->JS = 'get.js?' . BROWSER . '/' . THEME . '/' . APP . '/'
                        . ($data->WIDGETS ? $data->WIDGETS.','.APP : APP)
                        . '/' . JSVERSION
                        . (ACCESS >= DEBUG ? '/debug' : '');
                $data->CSS = 'get.css?' . BROWSER . '/' . THEME . '/' . APP . '/'
                        . ($data->WIDGETS ?  $data->WIDGETS.','.APP : APP)
                        . '/' . CSSVERSION
                        . (ACCESS >= DEBUG ? '/debug' : '');
                //common::theme($data);
                if (!(include 'themes/' . THEME . '/default.html')) {
                    echo sprintf(dgettext('common', '%s, theme not found! <br />
                                If you want change to default theme quickly, you can click %s.'),
                            THEME, '<a href="http://' . DOMAIN . '/default.thm">http://' . DOMAIN . '/default.thm</a>');
                }
                break;
            case 'xml': header('content-type: text/xml');
                echo xml::convert($data);
                break;
            case 'json': header('content-type: application/json');
                unset($data->APPS);
                echo json_encode($data);
                break;
            case 'text': header('content-type: text/plain');
                var_export($data);
                break;
        }
    }

    public static function result($status, $message = null, $fields = null, $redirect = null, $js = true, $format = FORMAT) {

        $statuses = array(200 => dgettext('common', 'Successfully'), 400 => dgettext('common', 'Alert'), 600 => dgettext('common', 'Error'), 800 => dgettext('common', 'System Error'));
        $dataObject = new stdClass();
        if (!$js) {
            header('location: http://' . DOMAIN . $redirect);
            exit;
        }
        $dataObject->code = $status;
        $dataObject->status = $statuses[$status];
        $dataObject->message = $message;
        if (ACCESS >= DEBUG) {
            //global $debug;
            $caller = debug_backtrace();
            $dataObject->debug = sprintf(dgettext('common', 'file: %s :: line: %s'), $caller[0]['file'], $caller[0]['line']);
            $dataObject->debug .= self::backtrace();
        } else
            $dataObject->debug = null;
        $dataObject->fields = $fields;
        $dataObject->redirect = $redirect;
        if ($format == 'object')
            return $dataObject; else {
            global $data;
            foreach ($dataObject as $k => $i)
                $data->$k = $i;
        }
        return $status >= 400 ? false : true;
    }

    public static function guide($class, $message) {
        global $data;
        $guide = new stdClass();
        $guide->class = $class;
        $guide->message = $message;
        $data->guide[] = $guide;
    }

    public static function template($filename, $i = null, $p = null, $c = null) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            $contents = ob_get_contents();
            ob_end_clean();
            return $contents;
        }
        return false;
    }

    /* public static function check($type,$subject){
      switch($type){
      case 'email':
      $pattern = '/^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+\.[a-z]{2,4}$/';
      break;
      case 'username':
      $pattern = '/^[0-9a-z.]{2,60}$/';
      break;
      case 'fullname':
      $pattern = '/^[^ ]{2,30} (.+)$/';
      break;
      }
      preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
      return $matches[0];
      } */

    public static function url($string) {
        $string = str_replace(array('ğ', 'ü', 'ş', 'ı', 'ö', 'ç', '.', '"', "'"), array('g', 'u', 's', 'i', 'o', 'c', '-', '-', '-'), mb_strtolower(stripslashes($string), "UTF-8"));
        foreach (str_split($string) as $i)
            $s .= in_array($i, array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', 1, 2, 3, 4, 5, 6, 7, 8, 9, '-')) ? $i : '_';
        foreach (str_split($s) as $k => $i)
            if ($i != '_' && $i != '-')
                break; $s = substr($s, $k, strlen($s));
        foreach (str_split(strrev($s)) as $k => $i)
            if ($i != '_' && $i != '-')
                break;
        return substr($s, 0, strlen($s) - $k);
    }

    public static function imageid($ID, $key = null) {
        return sha1($ID . ($key ? $key : KEY));
    }

    public static function money($number, $unit='TL') {
        $n = explode(',', number_format($number, 2, ',', '.'));
        return '<span class="number">' . $n['0'] . '</span><span class="decimal">,' . $n[1] . '</span><span class="unit"> ' . $unit . '</span>';
    }

    public static function baseEncode($data) {
        return str_replace('=', '', base64_encode($data));
    }

    public static function baseDecode($data) {
        return base64_decode($data);
    }

    public static function encode($data, $key = KEY) {
        $code = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, 'ecb',
                                mcrypt_create_iv(
                                        mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)
                        )
        );
        return urlencode($code);
    }

    public static function decode($code, $key = KEY) {
        $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode(urldecode($code)), 'ecb',
                        mcrypt_create_iv(
                                mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND
                        )
        );
        return (trim($data));
    }

    public static function nl2clean($data) {
        return str_replace(array("\n", "\r"), '', $data);
    }

    public static function quot($string) {
        return str_replace('"', '&quot;', $string);
    }

    public static function pager($a) {
        //print_r($a);
        $l = 5;
        $a['limit'] = $a['limit'] ? ($a['limit'] > 50 ? 50 : $a['limit']) : 10;
        $a['page'] = $a['page'] ? $a['page'] : 1;
        $a['pages'] = ceil($a['total'] / $a['limit']);
        if ($a['pages'] <= 1 && !$a['left'])
            return false;
        $a['links'][] = '<a ' . ($a['page'] > 1 ? 'href="' . $a['link'] . ($a['page'] - 1) . ',' . $a['limit'] : 'class="disabled') . '"><</a>';
        $a['links'][] = '<a ' . ($a['page'] > 1 ? 'href="' . $a['link'] . '1,' . $a['limit'] : 'class="selected') . '">1</a>';
        if ($a['pages'] <= $l) {
            for ($i = 2; $i <= $a['pages'] - 1; $i++) {
                $a['links'][] = '<a ' . ($i == $a['page'] ? 'class="selected' : 'href="' . $a['link'] . $i . ',' . $a['limit']) . '">' . $i . '</a>';
            }
        } elseif ($a['page'] < $l) {
            for ($i = 2; $i <= $l; $i++) {
                $a['links'][] = '<a ' . ($i == $a['page'] ? 'class="selected' : 'href="' . $a['link'] . $i . ',' . $a['limit']) . '">' . $i . '</a>';
            }
            $a['links'][] = '<a class="seperate">...</a>';
        } elseif ($a['pages'] - $a['page'] > $l) {
            $a['links'][] = '<a class="seperate">...</a>';
            for ($i = $a['page'] - ($l / 2 >> 0); $i <= $a['page'] + ($l / 2 >> 0); $i++) {
                $a['links'][] = '<a ' . ($i == $a['page'] ? 'class="selected' : 'href="' . $a['link'] . $i . ',' . $a['limit']) . '">' . $i . '</a>';
            }
            $a['links'][] = '<a class="seperate">...</a>';
        } else {
            $a['links'][] = '<a class="seperate">...</a>';
            for ($i = $a['pages'] - $l; $i <= $a['pages'] - 1; $i++) {
                $a['links'][] = '<a ' . ($i == $a['page'] ? 'class="selected' : 'href="' . $a['link'] . $i . ',' . $a['limit']) . '">' . $i . '</a>';
            }
        }
        if ($a['pages'] > 1
            )$a['links'][] = '<a ' . ($a['page'] < $a['pages'] ? 'href="' . $a['link'] . $a['pages'] . ',' . $a['limit'] : 'class="selected') . '">' . $a['pages'] . '</a>';
        $a['links'][] = '<a ' . ($a['page'] < $a['pages'] ? 'href="' . $a['link'] . ($a['page'] + 1) . ',' . $a['limit'] : 'class="disabled') . '">></a>';
        foreach (array_reverse($a['links']) as $i)
            $r .= $i;
        return '<div class="pager"><div class="left">' . $a['left'] . '</div>' . $r . '<div class="clear"></div></div>';
    }

    public static function mail($name, $to, $subject, $message, $a=false) {

        $textmessage = strip_tags(str_replace(array('<br>', '<br/>', '<br />'), array("\n\r", "\n\r", "\n\r"), $message));
        $message = self::template('themes/' . THEME . '/mail.html', $message);

        if (!MAILSMTP) {
            $to = "$name <$to>";
            $from = NAME . ' <' . (MAILADDR ? MAILADDR : ('no-reply@' . DOMAIN)) . '>';
            $boundary = sha1(time() . NAME);
            $headers = <<<HEADER
From: $from
MIME-Version: 1.0
Content-Type: multipart/alternative;
    boundary="$boundary"
HEADER;
            $message = <<<MESSAGE
--$boundary
Content-Type: text/plain; charset = "utf-8"
Content-Transfer-Encoding: 8bit

$textmessage

--$boundary
Content-Type: text/html; charset = "utf-8"
Content-Transfer-Encoding: 8bit

$message

--$boundary--
MESSAGE;
            return mail($to, $subject, $message, $headers);
        } else {
            if (!include 'apps/common/lib/phpMailer/class.phpmailer.php')
                return false;
            list($host, $port) = split(':', $a['mailsmtp'] ? $a['mailsmtp'] : MAILSMTP);
            $mail = new PHPMailer();
            $mail->isSMTP(); // telling the class to use SMTP

            $mail->SMTPAuth = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host = $host;                 // sets GMAIL as the SMTP server
            $mail->Port = $port ? $port : MAILPORT;  // set the SMTP port for the GMAIL server

            $mail->Username = $a['mailuser'] ? $a['mailuser'] : MAILUSER;  // GMAIL username
            $mail->Password = $a['mailpass'] ? $a['mailpass'] : MAILPASS;  // GMAIL password

            $mail->Host = $host; // SMTP server
            $mail->From = $a['from'] ? $a['from'] : ('no-reply@' . DOMAIN);
            $mail->FromName = $a['name'] ? $a['name'] : NAME;
            $mail->CharSet = 'utf-8';
            $mail->Subject = $subject;
            //// optional, comment out and test
            $mail->AltBody = $textmessage;
            $mail->MsgHTML($message);
            $mail->AddAddress($to, $name);
            //$mail->AddAttachment("images/phpmailer.gif");    // attachment
            //echo $mail->ErrorInfo;
            return $mail->Send();
        }
    }

    public static function age($date) {
        list($y, $m, $d) = explode(',', @date('Y,m,d', strtotime($date)));
        $age = @date('Y') - $y;
        return (@date('m') > $m || (@date('m') == $m && @date('d') >= $d)) ? $age : $age - 1;
    }

    public static function timediff($date) {
        $diff = @date('U') - @strtotime($date);
        $min = 60;
        $hour = 3600;
        $day = 86400;
        $week = 604800;
        $month = 2419200;
        $year = 29030400;
        if ($diff >= $year) {
            $r = sprintf(($d = $diff / $year) >= 2 ? dgettext('common', 'about %d years ago.') : dgettext('common', 'about %d year ago.'), $d);
        } elseif ($diff >= $month) {
            $r = sprintf(($d = $diff / $month) >= 2 ? dgettext('common', 'about %d months ago.') : dgettext('common', 'about %d month ago.'), $d);
        } elseif ($diff >= $week) {
            $r = sprintf(($d = $diff / $week) >= 2 ? dgettext('common', 'about %d weeks ago.') : dgettext('common', 'about %d week ago.'), $d);
        } elseif ($diff >= $day) {
            $r = sprintf(($d = $diff / $day) >= 2 ? dgettext('common', 'about %d days ago.') : dgettext('common', 'about %d day ago.'), $d);
        } elseif ($diff >= $hour) {
            $r = sprintf(($d = $diff / $hour) >= 2 ? dgettext('common', 'about %d hours ago.') : dgettext('common', 'about %d hour ago.'), $d);
        } elseif ($diff >= $min) {
            $r = sprintf(($d = $diff / $min) >= 2 ? dgettext('common', 'about %d mins ago.') : dgettext('common', 'about %d min ago.'), $d);
        } else {
            $r = sprintf(($d = $diff) >= 2 ? dgettext('common', 'about %d secs ago.') : dgettext('common', 'about %d sec ago.'), $d);
        }
        return $r;
    }

    public static function date($date, $short = 0, $lang = 'tr') {
        list($y, $m, $d, $h, $i, $s) = explode(',', @date('y,m,d,H,i,s', strtotime($date)));
        $h = (($h + 2) % 24);
        $h = ($h < 10) ? '0' . $h : $h;
        if (LANG == 'tr')
            return $d . ' ' . self::month($m) . ' ' . ($short ? substr($y, 2) : $y) . ' ' . (($i || $s) ? $h . ':' . $i : '');
        else
            return self::month($m) . ' ' . $d . ' ' . ($short ? substr($y, 2) : $y) . ' ' . (($i || $s) ? $h . ':' . $i : '');
    }

    public static function month($i) {
        $m = explode(',', dgettext('common', ',Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'));
        return $m[number_format($i)];
    }

    public static function cookie($cmd, $a) {
        switch ($cmd) {
            case 'set':
                foreach ($a as $k => $v)
                    @setcookie('uL[' . $k . ']', $v, time() + 604800, null, '.' . DOMAIN);
                break;
            case 'get':
                return $_COOKIE['uL'][$a];
                break;
            case 'del':
                foreach ($a as $k => $v)
                    @setcookie('uL[' . $k . ']', '0', time() - 3600, null, '.' . DOMAIN);
                break;
        }
    }

    public static function benchmark($data) {
        $data->finish = microtime(true) - $data->start;
        $configuration = round($data->configuration * 100 / $data->finish);
        $classes = round(($data->classes - $data->configuration) * 100 / $data->finish);
        $requests = round(($data->requests - $data->classes) * 100 / $data->finish);
        $bindtextdomain = round(($data->bindtextdomain - $data->requests) * 100 / $data->finish);
        $dbconnection = round(($data->dbconnection - $data->bindtextdomain) * 100 / $data->finish);
        $process = round(($data->process - $data->dbconnection) * 100 / $data->finish);
        $template = round(($data->finish - $data->process) * 100 / $data->finish);
        $bench = '
    		<dl id="benchmark">
                <h3>BENCHMARK</h3>
    		<dt>start</dt><dd><span style="width:1px"></span>&nbsp;</dd>
    		<dt>configuration</dt><dd title="' . $configuration . '%"><span style="width:' . $configuration . '%">&nbsp;</span></dd>
    		<dt>classes</dt><dd title="' . $classes . '%"><span style="margin-left:' . ($configuration) . '%;width:' . $classes . '%">&nbsp;</span></dd>
    		<dt>requests</dt><dd title="' . $requests . '%"><span style="margin-left:' . ($configuration + $classes) . '%;width:' . $requests . '%">&nbsp;</span></dd>
    		<dt>bindtextdomain</dt><dd title="' . $bindtextdomain . '%"><span style="margin-left:' . ($configuration + $classes + $requests) . '%;width:' . $bindtextdomain . '%">&nbsp;</span></dd>
    		<dt>dbconnection</dt><dd title="' . $dbconnection . '%"><span style="margin-left:' . ($configuration + $classes + $requests + $bindtextdomain) . '%;width:' . $dbconnection . '%">&nbsp;</span></dd>
    		<dt>process</dt><dd title="' . $process . '%"><span style="margin-left:' . ($configuration + $classes + $requests + $bindtextdomain + $dbconnection) . '%;width:' . $process . '%">&nbsp;</span></dd>
    		<dt>template</dt><dd title="' . $template . '%"><span style="margin-left:' . ($configuration + $classes + $requests + $bindtextdomain + $dbconnection + $process) . '%;width:' . $template . '%">&nbsp;</span></dd>
    		<dt>total</dt><dd>' . round($data->finish * 100) . 'ms</dd>
    		</dl>';
        return $bench;
    }

    public static function backtrace() {
        global $debug;
        //$trace = array_reverse(debug_backtrace());
        //$trace = array_reverse($debug);
        foreach ((array) $debug as $i) {
            //$args = '';
            //foreach ($i['args'] as $a) $args .= ','.(gettype($a)=='string'?$a:gettype($a));
            /* $log .= sprintf('<li><dt>%s %s %s( %s )</dt><dd>%s - %s: %s</dd></li>'
              ,$i['class'],$i['type'],$i['function'],substr($args,1),$i['file'],dgettext('common','line'),$i['line']); */


            $log .= sprintf('<li class="%s"><dt>%s</dt><dd>%s - %s: %s</dd><dd class="result">%s</dd></li>',
                            ($i['error'] ? 'error' : 'pass'), $i['query'], $i['file'], dgettext('common', 'line'), $i['line'],
                            ($i['error'] ? sprintf(dgettext('common', 'error: %s'), $i['error']) : dgettext('common', 'pass')));
        }
        //file_put_contents('data/osman.txt', $log);
        return sprintf('<ol id="backtrace"><h3>BACKTRACE</h3>%s</ol>', $log);
    }

    public static function debug($data) {
        echo '<div id="debug">
                <div id="return">
                <h3>DEBUG</h3>
                CODE: ' . $data->code . '<br/>
                STATUS: ' . $data->status . '<br/>
                MESSAGE: ' . $data->message . '<br/>
                FILE: ' . $data->debug
        . '</div>'
        . self::benchmark($data->bench)
        . '<div class="clear"></div>'
        . self::backtrace()
        . '</div>';
    }


}

?>